<?php
/**
 * Created by jinqiang on 2024/5/23 15:10.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Repository;


use App\Http\Models\Mysql\NnyyUserTable;

class FeishuRepository
{
    private $_app_access_token;

    private $_tenant_access_token;

    private $_sub;

    public function __construct($sub = "kz")
    {
        $res = $this->getAppAccessToken($sub);
        list($this->_sub, $this->_app_access_token, $this->_tenant_access_token) = [$sub, $res['app_access_token'] ?? "", $res['tenant_access_token'] ?? ""];
    }

    //获取自建应用的app_access_token
    public function getAppAccessToken($sub)
    {
        $subjects = array_column(config('scm.subject'), null, 'is_subject');
        $url = "https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal";
        $param = [
            'json' => json_encode([
                'app_id' => $subjects[$sub]['fs_app_id'],
                'app_secret' => $subjects[$sub]['fs_app_secret']
            ]),
            'headers' => ["Content-type:application/json; charset=utf-8","Accept:application/json"]
        ];
        $resp = httpCurl($url, $param);
        $res = json_decode($resp, true);
        return $res;
    }

    //获取user_access_token
    public function getUserAccessToken($code)
    {
        $url = "https://open.feishu.cn/open-apis/authen/v1/oidc/access_token";
        $param = [
            'json' => json_encode([
                'grant_type' => "authorization_code",
                'code' => $code
            ]),
            'headers' => [
                "Authorization:Bearer {$this->_app_access_token}",
                "Content-type:application/json; charset=utf-8"
            ]
        ];
        $resp = httpCurl($url, $param);
        $res = json_decode($resp, true);
        return $res;
    }

    //获取登录用户信息
    public function getUserInfo($code)
    {
        $res = $this->getUserAccessToken($code);
        $userAccessToken = $res['data']['access_token'] ?? "";
        $url = "https://open.feishu.cn/open-apis/authen/v1/user_info";
        $param = [
            'headers' => [
                "Authorization:Bearer {$userAccessToken}",
                "Content-type:application/json; charset=utf-8"
            ]
        ];
        $resp = httpCurl($url, $param, "get");
        $res = json_decode($resp, true);
        return $res;
    }

    //飞书回调消息的解密
    public static function decryptData($encryptStr, $sub = "kz")
    {
        $subjects = array_column(config('scm.subject'), null, 'is_subject');
        $encryptKey = $subjects[$sub]['fs_encrypt_key'];
        $message = base64_decode($encryptStr);
        $iv = substr($message, 0, 16);
        $encryptedEvent = substr($message, 16);
        $dataStr = openssl_decrypt($encryptedEvent, 'AES-256-CBC', hash('sha256', $encryptKey, true), OPENSSL_RAW_DATA, $iv);
        return json_decode($dataStr, true);;
    }

    //创建飞书审批
    public function createApproval($postData)
    {
        $url = "https://open.feishu.cn/open-apis/approval/v4/instances";
        $param = [
            "headers" => ['Content-Type:application/json','Authorization:'."Bearer {$this->_tenant_access_token}"],
            "json" => json_encode($postData)
        ];
        $resp = httpCurl($url, $param);
        $data = json_decode($resp, true);
        return $data;
    }

    //审批：上传图片、文件 https://open.feishu.cn/document/server-docs/approval-v4/file/upload-files#f19f3c9f
    public function upload($postData)
    {
        $url = "https://www.feishu.cn/approval/openapi/v2/file/upload";
        $param = [
            'json' => [
                'content' => new \CURLFile($postData['content']),
                'type' => $postData['type'],
                'name' => $postData['name']
            ],
            "headers" => ['Content-Type:multipart/form-data','Authorization:'."Bearer {$this->_tenant_access_token}"],
        ];
        $resp = httpCurl($url, $param, 'file');
        $data = json_decode($resp, true);
        return $data;
    }

    //消息：上传图片
    public function uploadImgMsg($postData)
    {
        $url = "https://open.feishu.cn/open-apis/im/v1/images";
        $param = [
            'json' => [
                'image' => new \CURLFile($postData['image']),
                'image_type' => $postData['image_type'],
            ],
            "headers" => ['Content-Type:multipart/form-data','Authorization:'."Bearer {$this->_tenant_access_token}"],
        ];
        $resp = httpCurl($url, $param, 'file');
        $data = json_decode($resp, true);
        return $data;
    }

    //发送消息 私聊、群消息
    public function sendMsg($postData, $type = 'user_id')
    {
        $url = "https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type={$type}";
        $param = [
            "headers" => ['Content-Type:application/json','Authorization:'."Bearer {$this->_tenant_access_token}"],
            "json" => json_encode($postData)
        ];
        $resp = httpCurl($url, $param);
        $data = json_decode($resp, true);
        return $data;
    }

    //批量获取用户信息
    public function getUsers($query)
    {
        $url = "https://open.feishu.cn/open-apis/contact/v3/users/batch?user_id_type=user_id&{$query}";
        $param = [
            "headers" => ['Content-Type:application/json','Authorization:'."Bearer {$this->_tenant_access_token}"]
        ];
        $resp = httpCurl($url, $param, 'get');
        $data = json_decode($resp, true);
        return $data;
    }

    //获取单个飞书实例审批详情
    public function getFlow($instanceCode)
    {
        $url = "https://open.feishu.cn/open-apis/approval/v4/instances/{$instanceCode}";
        $param = [
            "headers" => ['Content-Type:application/json','Authorization:'."Bearer {$this->_tenant_access_token}"]
        ];
        $resp = httpCurl($url, $param, 'get');
        $data = json_decode($resp, true);
        if($data['code'] !== 0){
            return ['code' => -1, 'msg' => '获取审批实例详情失败', 'data' => $data];
        }
        //评论
        $commentMap = [];
        if($data['data']['comment_list'] ?? []){
            foreach ($data['data']['comment_list'] as $item){
                $commentMap[$item['user_id']][] = $item['comment'];
            }
        }
        $taskList = [];
        $userIds = array_merge([$data['data']['user_id']], array_column($data['data']['task_list'], 'user_id'));
        $column = $this->_sub."_feishu_user_id";
        $userList = (new NnyyUserTable())->whereIn($column, $userIds)->get(['name', $column])->toArray();
        $userMap = array_column($userList, 'name', $column);
        foreach ($data['data']['task_list'] as $item){
            if(!isset($item['user_id'])){
                continue;
            }
            $taskList[] = [
                'approval_name' => $data['data']['approval_name'],//实例id
                'instance_code' => $data['data']['instance_code'],//审批id
                'approval_status' => $data['data']['status'],
                'name' => $userMap[$item['user_id']] ?? $item['user_id'],
                'user_id' => $item['user_id'],
                'comment' => $commentMap[$item['user_id']] ?? [],
                'end_time' => !empty($item['end_time']) ? date('Y-m-d H:i:s', $item['end_time']/1000) : "",//审批时间
                'node_name' => $item['node_name'],
                'status' => $item['status'],
                'type' => $item['type']
            ];
        }
        array_unshift($taskList, [
            'approval_name' => $data['data']['approval_name'],//实例id
            'instance_code' => $data['data']['instance_code'],//审批id
            'approval_status' => $data['data']['status'],
            'name' => $userMap[$data['data']['user_id']],
            'user_id' => $data['data']['user_id'],
            'comment' => $commentMap[$data['data']['user_id']] ?? [],
            'end_time' => date('Y-m-d H:i:s', $data['data']['start_time']/1000),//发起时间
            'node_name' => '发起审批',
            'status' => "START",
            "type" => "AND"
        ]);
        //抄送
        $csObj = end($data['data']['timeline']);
        $csUserIds = array_column($csObj['cc_user_list'] ?? [], 'user_id');
        if(!empty($csUserIds)){
            $csUserList = (new NnyyUserTable())->whereIn($column, $csUserIds)->get(['name', $column])->toArray();
            $taskList[] = [
                'status' => "MESSAGE",
                'user_list' => $csUserList
            ];
        }
        //结束
        if($data['data']['status'] != "PENDING"){
            $taskList[] = [
                'status' => "END"
            ];
        }
        return ['code' => 0, 'msg' => '获取审批实例详情', 'data' => $taskList];
    }
}
